package seafileclient

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
)

func httpReq(url, reqType string, postData []byte) (int, string) {

	client := &http.Client{}
	var request *http.Request
	var err error
	if reqType == "GET" {
		request, err = http.NewRequest(reqType, url, nil)

	} else if reqType == "POST" {
		request, err = http.NewRequest(reqType, url, bytes.NewReader(postData))

	} else {
		return 0, ""
	}
	if err != nil {
		fmt.Println("NewRequest错误", err)
	}
	// cookie := &http.Cookie{Name: "userId", Value: strconv.Itoa(12345)}
	// request.AddCookie(cookie) //reques 中添加cookie
	//设置request的header
	// request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

	// request.Header.Set("Cache-Control", "max-age=0")
	// request.Header.Set("Connection", "keep-alive")
	request.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
	request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
	request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
	request.Header.Set("Content-Type", "application/json")
	if token != "" {
		request.Header.Set("Accept", "application/json; indent=4")
		request.Header.Set("Authorization", "Token "+token)
		// fmt.Println("token", token)
	}
	// fmt.Println("request", request)
	response, err := client.Do(request)
	if err != nil {
		fmt.Println("网络请求失败", err)
	}
	defer response.Body.Close()
	// fmt.Println(response)
	if response.StatusCode == 200 {
		r, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Println(err)
		}
		return response.StatusCode, string(r)
	}
	return response.StatusCode, ""

}

func httpGet(url string) {
	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println(err)
	}
	cookie := &http.Cookie{Name: "userId", Value: strconv.Itoa(12345)}
	request.AddCookie(cookie) //reques 中添加cookie
	//设置request的header
	// request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	// request.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
	// request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
	// request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
	// request.Header.Set("Cache-Control", "max-age=0")
	// request.Header.Set("Connection", "keep-alive")
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer response.Body.Close()
	fmt.Println(response.StatusCode)
	if response.StatusCode == 200 {
		r, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(r))
	}

	// resp, err := http.Get("https://yunpan.zgdgz.org:39843")
	// if err != nil {
	// 	fmt.Println("err", err)
	// }
	// defer resp.Body.Close()
	// body, err := ioutil.ReadAll(resp.Body)
	// if err != nil {
	// 	fmt.Println("err", err)
	// }
	// fmt.Println(string(body))
}
